package com.soft.service;

import java.time.LocalDate;
import java.time.LocalTime;
import java.math.BigDecimal;
import java.sql.Timestamp;  // 修正了Timestamp的导入包
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.soft.entity.Orderlist;
import com.soft.mapper.OrderlistMapper;
import com.soft.entity.Orderlistdetails;
import com.soft.mapper.OrderlistdetailsMapper;

@Service
public class OrderlistService {
    @Autowired
    private OrderlistMapper orderlistMapper;
    @Autowired
    private OrderlistdetailsMapper orderlistdetailsMapper;


    // 移除了时间参数，改为内部自动获取
    public Long addorderlist(Long userId, Long deskId, String orderlistStatus, 
                           Long employeeId, Long orderlistTotalprice, Long storeId) {
        Orderlist orderlist = new Orderlist();
        orderlist.setUserId(userId);
        orderlist.setDeskId(deskId);
        // 自动设置为当前系统时间
        orderlist.setOrderlistTime(new Timestamp(new Date().getTime()));
        orderlist.setOrderlistStatus(orderlistStatus);  // 修正了参数名的拼写错误
        orderlist.setEmployeeId(employeeId);
        orderlist.setOrderlistPrice(orderlistTotalprice);
        orderlist.setStoreId(storeId);
        orderlistMapper.insert(orderlist);
        return orderlist.getOrderlistId();
    }
    
    public int updateStatus(Long orderlistId, String orderlistStatus) {
        Orderlist orderlist = orderlistMapper.selectById(orderlistId);
        if (orderlist == null) {
            return 0;
        }

        // 原来的状态
        String oldStatus = orderlist.getOrderlistStatus();

        // 查订单明细
        QueryWrapper<Orderlistdetails> qw = new QueryWrapper<>();
        qw.eq("orderlist_id", orderlistId);
        List<Orderlistdetails> details = orderlistdetailsMapper.selectList(qw);

        // 1. 状态改为 已取消 → 回补库存
        if (!"已取消".equals(oldStatus) && "已取消".equals(orderlistStatus)) {
            for (Orderlistdetails detail : details) {
                orderlistdetailsMapper.restoreStockByName(detail.getFoodName(), detail.getFoodCount());
            }
        }

        // 2. 状态由 已取消 改为 其他 → 扣减库存
        if ("已取消".equals(oldStatus) && !"已取消".equals(orderlistStatus)) {
            for (Orderlistdetails detail : details) {
                orderlistdetailsMapper.reduceStockByName(detail.getFoodName(), detail.getFoodCount());
            }
        }

        // 更新订单状态
        orderlist.setOrderlistStatus(orderlistStatus);
        return orderlistMapper.updateById(orderlist);
    }


    public List<Orderlist> queryByStoreId(Long storeId){
        QueryWrapper<Orderlist> qw = new QueryWrapper<>();
        qw.eq("store_id", storeId);
        return orderlistMapper.selectList(qw);
    }

    
    //根据userID更新数据（原有方法，保持不变）
    public int updateOrderlist(Long userId, Long deskId, String orderlistStatus, 
            Long employeeId, Long orderlistTotalprice, Long storeId) {
    	Orderlist orderlist = new Orderlist();
    	orderlist.setUserId(userId);
    	orderlist.setDeskId(deskId);
    	orderlist.setOrderlistStatus(orderlistStatus);
    	orderlist.setEmployeeId(employeeId);
    	orderlist.setOrderlistPrice(orderlistTotalprice);
    	orderlist.setStoreId(storeId);
    	return orderlistMapper.updateById(orderlist);
    }
    public List<Orderlist> queryByuserId(Long userId){
		QueryWrapper<Orderlist> qw = new QueryWrapper<>();
		qw.eq("user_id", userId);
		List<Orderlist> orderlistList = orderlistMapper.selectList(qw);
		return orderlistList;
	}
    public List<Orderlist> findAllByStore(Long storeId) {
        return orderlistMapper.selectList(
            new QueryWrapper<Orderlist>()
                .eq("store_id", storeId)
                .orderByDesc("orderlist_id")
        );
    }

    public Orderlist queryById(Long orderlistId) {
        
        return orderlistMapper.selectById(orderlistId);
    }
    public List<Orderlist> searchByTime(Long storeId, Timestamp start, Timestamp end) {
        QueryWrapper<Orderlist> qw = new QueryWrapper<>();
        qw.eq("store_id", storeId)
          .ge("orderlist_time", start)
          .le("orderlist_time", end)
          // 新增：只查询状态为“已完成”的订单
          .eq("orderlist_status", "已完成")  // 假设状态值为“已完成”，根据实际数据库值调整
          .orderByDesc("orderlist_time");
        return orderlistMapper.selectList(qw);
    }
    

    public BigDecimal getTotalPriceByDay(Date date) {
        // 1. 格式化日期为"yyyy-MM-dd"字符串，用于匹配当天订单
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String targetDate = sdf.format(date);

        // 2. 构建查询条件：当天订单 + 状态为"已完成"
        QueryWrapper<Orderlist> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("orderlist_time", targetDate + "%")  // 匹配当天所有时间（如"2023-10-01 00:00:00"至"2023-10-01 23:59:59"）
                    .eq("orderlist_status", "已完成")         // 仅统计已完成状态的订单
                    .orderByDesc("orderlist_time");            // 按订单时间倒序排列

        // 3. 查询符合条件的订单列表
        List<Orderlist> orderlists = orderlistMapper.selectList(queryWrapper);

        // 4. 累加已完成订单的总金额
        BigDecimal totalPrice = BigDecimal.ZERO;
        for (Orderlist order : orderlists) {
            Long priceLong = order.getOrderlistPrice();  // 获取订单金额（假设存储为Long类型）
            if (priceLong != null) {                     // 避免空指针异常
                BigDecimal priceBigDecimal = BigDecimal.valueOf(priceLong);
                totalPrice = totalPrice.add(priceBigDecimal);  // 累加金额
            }
        }

        return totalPrice;
    }
    
    
    
    
    public List<Long> getOrderlistIdsByDay(Date date) {
        // 构建日期查询条件（当天00:00:00到23:59:59）
        Timestamp startTime = new Timestamp(date.getTime());
        startTime.setHours(0);
        startTime.setMinutes(0);
        startTime.setSeconds(0);
        
        Timestamp endTime = new Timestamp(date.getTime());
        endTime.setHours(23);
        endTime.setMinutes(59);
        endTime.setSeconds(59);
        
        // 查询该时间段内的所有订单ID
        QueryWrapper<Orderlist> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("orderlist_time", startTime, endTime)
                   .select("orderlist_id");
        
        List<Orderlist> orderlists = orderlistMapper.selectList(queryWrapper);
        
        // 提取订单ID列表
        List<Long> orderlistIds = new ArrayList<>();
        for (Orderlist orderlist : orderlists) {
            orderlistIds.add(orderlist.getOrderlistId());
        }
        
        return orderlistIds;
    }
    /**
     * 根据日期查询该日所有商品的销售总量
     * @param date 要查询的日期
     * @return 键为商品名称，值为总销量的Map
     */
    public Map<String, Long> getGoodsTotalCountByDay(Date date) {
        // 1. 获取该日期的所有订单ID
        List<Long> orderlistIds = getOrderlistIdsByDay(date);
        if (orderlistIds.isEmpty()) {
            return new HashMap<>(); // 无订单时返回空Map
        }
        
        // 2. 根据订单ID列表查询所有订单详情
        // 注意类名规范：Java类名应使用驼峰式且首字母大写
        QueryWrapper<Orderlistdetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("orderlist_id", orderlistIds);
        
        // Mapper命名也应遵循驼峰式规范
        List<Orderlistdetails> detailsList = orderlistdetailsMapper.selectList(queryWrapper);
        
        // 3. 统计每个商品的总销量
        // 修正：将Map的value类型改为Long，与count类型保持一致
        Map<String, Long> goodsCountMap = new HashMap<>();
        for (Orderlistdetails detail : detailsList) {
            String goodName = detail.getFoodName(); // 商品名称字段
            Long count = detail.getFoodCount(); // 商品数量字段（Long类型）
            
            if (goodName != null && count != null) {
                // 修正：使用Long类型进行累加
                goodsCountMap.put(goodName, 
                    goodsCountMap.getOrDefault(goodName, 0L) + count);
            }
        }
        
        return goodsCountMap;
    }

    public class DateFormatUtil {
        // 中国大陆日期格式：yyyy年MM月dd日
        private static final SimpleDateFormat CHINESE_DATE_FORMAT = new SimpleDateFormat("yyyy年MM月dd日");
        
        /**
         * 将Date转换为中国大陆格式字符串
         */
        public static String formatChineseDate(Date date) {
            if (date == null) {
                return "";
            }
            return CHINESE_DATE_FORMAT.format(date);
        }
    }
    /**
     * 根据日期查询该日所有订单的orderlist_id、user_id和employee_id
     * @param date 要查询的日期
     * @return 包含订单ID、用户ID和员工ID的Map列表
     */
    public List<Map<String, Long>> getOrderIdsByDay(Date date) {
        // 1. 构建日期查询条件（当天00:00:00到23:59:59）
        Timestamp startTime = new Timestamp(date.getTime());
        startTime.setHours(0);
        startTime.setMinutes(0);
        startTime.setSeconds(0);
        
        Timestamp endTime = new Timestamp(date.getTime());
        endTime.setHours(23);
        endTime.setMinutes(59);
        endTime.setSeconds(59);
        
        // 2. 查询该时间段内的订单，只选择需要的字段
        QueryWrapper<Orderlist> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("orderlist_time", startTime, endTime)
                   .select("orderlist_id", "user_id", "employee_id")
                   .orderByDesc("orderlist_time");
        
        // 3. 执行查询
        List<Orderlist> orderlists = orderlistMapper.selectList(queryWrapper);
        
        // 4. 转换为只包含所需字段的Map列表
        List<Map<String, Long>> resultList = new ArrayList<>();
        for (Orderlist order : orderlists) {
            Map<String, Long> orderMap = new HashMap<>();
            orderMap.put("orderlistId", order.getOrderlistId());
            orderMap.put("userId", order.getUserId());
            orderMap.put("employeeId", order.getEmployeeId());
            resultList.add(orderMap);
        }
        
        return resultList;
    }
    public Map<String, Long> getMonthlyGoodsSales() {
        LocalDate now = LocalDate.now();
        LocalDate firstDay = now.withDayOfMonth(1);
        LocalDate lastDay = now.withDayOfMonth(now.lengthOfMonth());
        Timestamp start = Timestamp.valueOf(firstDay.atStartOfDay());
        Timestamp end = Timestamp.valueOf(lastDay.atTime(LocalTime.MAX));
        
        QueryWrapper<Orderlist> qw = new QueryWrapper<>();
        qw.between("orderlist_time", start, end)
          .eq("orderlist_status", "已完成")
          .select("orderlist_id");
        List<Orderlist> orders = orderlistMapper.selectList(qw);
        
        List<Long> orderIds = orders.stream().map(Orderlist::getOrderlistId).collect(Collectors.toList());
        if (orderIds.isEmpty()) {
            return new HashMap<>();
        }
        
        QueryWrapper<Orderlistdetails> dw = new QueryWrapper<>();
        dw.in("orderlist_id", orderIds);
        List<Orderlistdetails> details = orderlistdetailsMapper.selectList(dw);
        
        Map<String, Long> sales = new HashMap<>();
        for (Orderlistdetails d : details) {
            String name = d.getFoodName();
            Long count = d.getFoodCount();
            if (name != null && count != null) {
                sales.put(name, sales.getOrDefault(name, 0L) + count);
            }
        }
        return sales;
    }
 // 分页查询门店订单
    public Page<Orderlist> findPageByStore(Long storeId, int page, int size) {
        QueryWrapper<Orderlist> qw = new QueryWrapper<>();
        qw.eq("store_id", storeId).orderByDesc("orderlist_id");
        return orderlistMapper.selectPage(new Page<>(page, size), qw);
    }

}